package com.hmdp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) throws InterruptedException {
       /* String idKey = CACHE_SHOP_KEY + id;
        //TODO 1.从Redis查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(idKey);
        //TODO 2.判断缓存是否存在，存在直接返回，不存在查数据库
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //TODO 3.判断数据库中是否存在数据，存在写入缓存，不存在返回错误
        Shop shop = baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(shop)){
            //return Result.fail("商铺不存在");
            //TODO 防止缓存击穿,加载到数据库不存在的数据时，像缓存中添加空数据


        }
        stringRedisTemplate.opsForValue().set(idKey,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);*/

        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        return Result.ok();


    }

    @Override
    public Result redisUpdateById(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("商铺不能为空");
        }
        //TODO 1.先更新数据库
        updateById(shop);
        //TODO 2.删除缓存
        String idKey = CACHE_SHOP_KEY + shop.getId();
        stringRedisTemplate.delete(idKey);
        return Result.ok("商铺更新成功");
    }
}
